const AUTHORIZER_APPID = 'wx36bea992a3856d4a'; // mofa
// var AUTHORIZER_APPID = 'wx022ec8687b780a34'; // panx

const SHAKE_THRESHOLD = 2000; // 速度

const COUPON = '/api/may-promo/promo-coupon';

/* global mayPromoMixin, Vue, weui, axios */
function initShakePage() {
  return new Vue({
    el: '#root',
    mixins: [mayPromoMixin],
    data() {
      return {
        last_x: 0,
        last_y: 0,
        last_z: 0,
        last_update: 0, // 上一次时间
        coupons: [],
        is_play: false,
        is_visible_modal: false,
        is_visible_coupons: false, // 是否显示卡券?
        user_info: null,
      };
    },

    mounted() {
      // var timer = window.setTimeout(this.reloadPage, 3000);
      const self = this;
      const loading = weui.loading('加载中...');
      this.resolveOpenId()
        .then((openid) => {
          self.openid = openid;
          // window.clearTimeout(timer); // 清除
          // 请求coupon列表
          self.handleFetchCouponIndex(openid);

          // 请求用户信息
          self.fetchUserInfo(openid)
            .then((userInfo) => {
              if (userInfo) {
                self.user_info = userInfo;
              }
            });
        })
        .then(() => {
          loading.hide();
        });
      this.listenDeviceMotion();
    },

    methods: {

      /**
       *  获取 coupon
       */
      createCoupon() {
        // 是否有卡券?
        if (this.hasCoupon()) {
          this.showCouponsModal();
          weui.alert('只能参与一次抽奖');
          return;
        }

        // 正在请求
        if (this.is_play) {
          return;
        }
        this.is_play = true;

        this.storeCoupons();
      },

      /**
       * @return {Promise<T>}
       */
      storeCoupons() {
        return axios
          .post(COUPON, {
            appid: AUTHORIZER_APPID,
            openid: this.openid,
          })
          .then((response) => {
            if (response.data.code !== 0) {
              throw new Error(response.data.error);
            }

            this.coupons = response.data.coupon_lists;
            this.showCouponsModal();
          })
          .catch((error) => {
            weui.alert(error.message);
            console.error(error);
          })
          .then(() => {
            this.is_play = false;
          });
      },

      /**
       *  判断是否已经订阅
       */
      hasSubscribe() {
        return this.user_info && parseInt(this.user_info.subscribe, 10) === 1;
      },

      /**
       *  是否有卡券
       * @returns {boolean}
       */
      hasCoupon() {
        return !! this.coupons.length;
      },

      showCouponsModal() {
        this.is_visible_coupons = true;
      },

      /**
       *  关闭卡券列表
       */
      closeCouponsModal() {
        this.is_visible_coupons = false;
      },

      /**
       *  监听设备运动
       */
      listenDeviceMotion() {
        window.addEventListener('devicemotion', this.handleDeviceMotion, false);
      },


      /**
       * 处理设备运动
       */
      handleDeviceMotion(eventData) {
        const acceleration = eventData.accelerationIncludingGravity;
        const curTime = new Date().getTime();
        if ((curTime - this.last_update) > 100) {
          const diffTime = curTime - this.last_update;
          this.last_update = curTime;
          const { x, y, z } = acceleration;
          const speed = (Math.abs((x + y + z) - this.last_x - this.last_y - this.last_z)
            / diffTime) * 10000;
          if (speed > SHAKE_THRESHOLD) {
            this.shake();
          }
          this.last_x = x;
          this.last_y = y;
          this.last_z = z;
        }
      },

      /**
       *  摇一摇
       */
      shake() {
        this.createCoupon();
      },

      /**
       *  关闭modal
       */
      closeQrcodeModal() {
        this.is_visible_modal = false;
      },

      showQrcodeModal() {
        this.is_visible_modal = true;
      },

      /**
       *  颜色类名
       */
      getClassName(discount) {
        const value = parseInt(discount, 10);
        const classObject = {
          purple: false,
          yellow: false,
          blue: false,
          default: false,
        };
        switch (value) {
          case 500:
            classObject.purple = true;
            break;
          case 300:
            classObject.yellow = true;
            break;
          case 200:
            classObject.blue = true;
            break;
          default:
            classObject.blue = true;
            break;
        }
        return classObject;
      },

      /**
       * 请求卡券列表
       * @param openid
       */
      handleFetchCouponIndex(openid) {
        const self = this;
        this.fetchCouponIndex({
          appid: AUTHORIZER_APPID,
          openid,
        }).then((coupons) => {
          if (coupons instanceof Array) {
            self.coupons = coupons;
          }
        });
      },

      checkCoupons() {
        // 是否订阅
        this.closeCouponsModal();
        this.showQrcodeModal();

        // window.open(`${location.origin}/may-promo/coupon/index.html?v${Math.random()}`);
      },

      /**
       *  超时重载
       */
      reloadPage() {
        window.location.reload();
      },


    },

  });
}

initShakePage();

